#include "jobthread.h"
#include "jobmanager.h"
#include "job.h"

namespace gecko
{

	JobThread::JobThread(JobManager * jobManager)
		: m_jobManager(jobManager)
		, m_currentJob(NULL)
		, m_run(true)
	{

	}

	void JobThread::Process()
	{
		if (m_currentJob)
		{
			m_currentJob->Process();
		}

		while ( m_run )
		{
			// Wait for the thread to be resumed
			m_threadEvent.Wait();

			if ( m_currentJob )
			{    
				// run job then delete it
				// TODO: use smart pointer
				m_currentJob->Process();

				m_currentJob = NULL;

				//GT3_SAFE_DELETE(m_task);
				m_jobManager->DistributeJob(this);

				if ( !m_currentJob )
				{
					// pause thread until next task
					m_threadEvent.Reset();
				}
			}
		}
	}

	void JobThread::SetCurrentJob( Job * job )
	{
		m_currentJob = job;

		// resume thread
		m_threadEvent.Signal();
	}

	void JobThread::KillProcessing()
	{
		// resume thread
		m_threadEvent.Signal();

		m_run = false;
	}

}
